package com.xxh.kfc.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 拦截所有food相关请求,支付，添加到购物车，下单
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = {"/food/pay","/car.jsp","/order/*","/food/addcar"})
public class LoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        HttpSession session = request.getSession();
        Object user = session.getAttribute("userDetail");
        if (user != null) {
            //如果已经登录，就可以放行了
            chain.doFilter(req, resp);
        } else {
            //要是没有登录，重写登录
            response.sendRedirect(request.getContextPath() + "/login.jsp?info=2");
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
